<template>
  <el-header style="padding: 0; border-bottom: 1px solid #e4e7ed;">
    <el-menu
      mode="horizontal"
      :default-active="activeIndex"
      style="border-bottom: none;"
      @select="handleMenuSelect"
    >
      <!-- Logo -->
      <div style="display: flex; align-items: center; padding: 0 20px; margin-right: 20px;">
        <el-text size="large" style="font-weight: 600; color: #303133;">
          Order System
        </el-text>
      </div>

      <!-- 主导航菜单 -->
      <el-menu-item
        v-for="item in accessibleMenuItems"
        :key="item?.path || 'unknown'"
        :index="item?.path || '/'"
      >
        <el-icon style="margin-right: 8px;">
          <component :is="getIconComponent(item?.icon || 'house')" />
        </el-icon>
        <span>{{ item?.name || 'Unknown' }}</span>
      </el-menu-item>

      <!-- 右侧菜单 -->
      <div style="margin-left: auto; display: flex; align-items: center; padding-right: 20px;">
        <!-- 网络状态指示器 -->
        <el-tag v-if="!isOnline" type="danger" size="small" style="margin-right: 16px;">
          <el-icon style="margin-right: 4px;">
            <Warning />
          </el-icon>
          Offline
        </el-tag>

        <!-- 用户下拉菜单 -->
        <el-dropdown @command="handleUserMenuCommand">
          <span style="cursor: pointer; display: flex; align-items: center;">
            <el-avatar :size="32" style="margin-right: 8px;">
              <el-icon><User /></el-icon>
            </el-avatar>
            <span style="margin-right: 4px;">{{ authStore.user?.username }}</span>
            <el-icon><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon style="margin-right: 8px;"><User /></el-icon>
                Profile
              </el-dropdown-item>
              <el-dropdown-item command="settings">
                <el-icon style="margin-right: 8px;"><Setting /></el-icon>
                Settings
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon style="margin-right: 8px;"><SwitchButton /></el-icon>
                Logout
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-menu>
  </el-header>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { getGlobalState } from '../composables/useGlobalState'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  Setting,
  SwitchButton,
  ArrowDown,
  Warning,
  House,
  Document,
  UserFilled,
  Tools
} from '@element-plus/icons-vue'

// 路由和store
const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const globalState = getGlobalState()

// 响应式数据
const showMobileMenu = ref(false)

// 计算属性
const isOnline = computed(() => globalState.isOnline)
const accessibleMenuItems = computed(() => {
  try {
    const items = globalState.accessibleMenuItems
    console.log('Menu items:', items)

    // 确保返回有效的菜单项数组
    if (!Array.isArray(items)) {
      console.warn('accessibleMenuItems is not an array:', items)
      return []
    }

    // 过滤掉没有path属性的项目，并确保每个项目都有必要的属性
    return items.filter(item => {
      return item &&
             typeof item === 'object' &&
             typeof item.path === 'string' &&
             typeof item.name === 'string' &&
             item.path.length > 0
    })
  } catch (error) {
    console.error('Error in accessibleMenuItems:', error)
    return []
  }
})
const activeIndex = computed(() => route.path)

// 图标映射
const iconMap: Record<string, any> = {
  'house': House,
  'home': House,
  'document': Document,
  'user': UserFilled,
  'tools': Tools,
  'setting': Setting,
  'cog': Tools
}

// 获取图标组件
function getIconComponent(iconName: string) {
  return iconMap[iconName] || House
}

// 处理菜单选择
function handleMenuSelect(index: string) {
  if (index !== route.path) {
    router.push(index)
  }
}

// 处理用户菜单命令
async function handleUserMenuCommand(command: string) {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm(
          'Are you sure you want to logout?',
          'Confirm Logout',
          {
            confirmButtonText: 'Logout',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
        )
        
        await authStore.logout()
        ElMessage.success('Logged out successfully')
        router.push('/login')
      } catch (error) {
        // 用户取消登出
        if (error !== 'cancel') {
          console.error('Logout failed:', error)
          ElMessage.error('Logout failed')
        }
      }
      break
  }
}
</script>

<style scoped>
.el-header {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-menu--horizontal {
  border-bottom: none !important;
}

.el-menu--horizontal .el-menu-item {
  border-bottom: 2px solid transparent;
}

.el-menu--horizontal .el-menu-item.is-active {
  border-bottom-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

.el-menu--horizontal .el-menu-item:hover {
  background-color: var(--el-color-primary-light-9);
}
</style>
